import Router from "vue-router";
import router from "@/router";
import store from "@/store";

/**
 * 获取uuid
 */
export function getUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(
      16
    );
  });
}

export function setUrl(url, params) {
  for (var k in params) {
    let value = params[k] !== undefined ? params[k] : "";
    url += `&${k}=${value}`;
  }
  return url;
}

export function getMathRand(num) {
  let random = "";
  for (var i = 0; i < num; i++) {
    random += Math.floor(Math.random() * 10);
  }
  return random;
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  return (
    JSON.parse(sessionStorage.getItem("permissions") || "[]").indexOf(key) !==
      -1 || false
  );
}

/**
 * 树形数据转换
 * @param {*} data list数据
 * @param {*} id 主键ID
 * @param {*} pid 上级ID
 * @param childrenKey 子list数据的key
 */
export function treeDataTranslate(
  data,
  id = "id",
  pid = "parentId",
  childrenKey = "children"
) {
  let mapTree = ListToTree(data, id, pid, childrenKey);
  return mapTree.data;
}

export function ListToTree(
  data,
  id = "id",
  pid = "parentId",
  childrenKey = "children"
) {
  let res = [];
  let temp = {};
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]][childrenKey]) {
        temp[data[k][pid]][childrenKey] = [];
      }
      if (!temp[data[k][pid]]["_level"]) {
        temp[data[k][pid]]["_level"] = 1;
      }
      data[k]["_level"] = temp[data[k][pid]]._level + 1;
      temp[data[k][pid]][childrenKey].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return { map: temp, data: res };
}

export function getPropertyList(array, key) {
  var list = [];
  for (var i = 0; i < array.length; i++) {
    list.push(array[i][key]);
  }
  return list;
}

/**
 * 根据orgNo翻译为orgName
 * @param orgNo
 */
export function transOrg(orgNo) {
  let orgList = JSON.parse(sessionStorage.getItem("orgList") || "[]");
  if (orgList.length > 0) {
    for (let i = 0; i < orgList.length; i++) {
      if (orgList[i].orgNo === orgNo) {
        return orgList[i].orgName;
      }
    }
  }
  return "--";
}

/**
 * 根据userId翻译为realName
 * @param userId
 */
export function transUser(userId) {
  return "--";

  // let userList = JSON.parse(sessionStorage.getItem('userList') || '[]')
  // if (userList.length > 0) {
  //   for (let i = 0; i < userList.length; i++) {
  //     if (userList[i].userId === userId) {
  //       return userList[i].realName
  //     }
  //   }
  // }
}

export function transDict(code, value) {
  if (!value && value !== 0) {
    return "--";
  }
  let dictList = JSON.parse(sessionStorage.getItem("dictList") || "[]");
  if (dictList.length > 0) {
    for (let i = 0; i < dictList.length; i++) {
      if (
        dictList[i].code === code &&
        dictList[i].value.toString() === value.toString()
      ) {
        return dictList[i].name;
      }
    }
  }
  return "--";
}

//根据字典值获取字典编码
export function transDictReverse(code, value) {
  if (!value && value !== 0) {
    return "--";
  }
  let dictList = JSON.parse(sessionStorage.getItem("dictList") || "[]");
  if (dictList.length > 0) {
    for (let i = 0; i < dictList.length; i++) {
      if (
        dictList[i].code === code &&
        dictList[i].name.toString() === value.toString()
      ) {
        return dictList[i].value;
      }
    }
  }
  return "--";
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
  store.commit("resetStore");
  var storage = window.localStorage;
  storage.clear();
  router.options.isAddDynamicMenuRoutes = false;
}

export function setTokenModel(tokenModel) {
  window.localStorage.setItem("$$tokenModel", JSON.stringify(tokenModel));
}

export function setToken(token) {
  setTokenModel({ token: token });
}

export function getToken() {
  let tokenModel = window.localStorage.getItem("$$tokenModel");
  if (tokenModel) {
    let tokenModelJson = JSON.parse(tokenModel);
    return tokenModelJson.token;
  } else {
    return null;
  }
}

export function getUrlKey(name) {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || [""])[0].replace(/\+/g, "%20")
    ) || null
  );
}

/**
 *  自定义表头列宽
 */
export function flexColumnWidth(str) {
  let flexWidth = 0;
  for (const char of str) {
    if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
      // 如果是英文字符，为字符分配8个单位宽度
      flexWidth += 15;
    } else if (char >= "\u4e00" && char <= "\u9fa5") {
      // 如果是中文字符，为字符分配20个单位宽度
      flexWidth += 25;
    } else {
      // 其他种类字符，为字符分配25个单位宽度
      flexWidth += 30;
    }
  }
  if (flexWidth < 50) {
    // 设置最小宽度
    flexWidth = 200;
  }
  if (flexWidth > 250) {
    // 设置最大宽度
    flexWidth = 250;
  }
  return flexWidth;
}

// 将数组转化成树结构
export function arrayToTree(
  array = [],
  options = { id: "id", pid: "pid", children: "children" }
) {
  let array_ = []; // 创建储存剔除叶子节点后的骨架节点数组
  let unique = {}; // 创建盒子辅助本轮children合并去重
  array.forEach((item) => {
    // 适应el-tree-transfer 将根节点pid重置为 0
    let root = ["undefined", undefined, null].includes(item[options.pid]);
    if (root) item[options.pid] = 0;
    // 筛选可以插入当前节点的所有子节点
    let childrenArray = array.filter(
      (it) => it[options.pid] === item[options.id]
    );
    if (item.children && item.children instanceof Array) {
      // 去重合并数组
      item.children.map((i) => (unique[i[options.id]] = 1));
      item.children.push(
        ...childrenArray.filter((i) => unique[i[options.id]] !== 1)
      );
    } else {
      item.children = childrenArray;
    }
    // 当children_array有数据时插入下一轮array_，当无数据时将最后留下来的根节点树形插入数组
    let hasChildren = childrenArray.length > 0;
    if (hasChildren || (!hasChildren && [0, "0"].includes(item[options.pid]))) {
      array_.push(item);
    }
  });
  // 当数组内仅有根节点时退出，否组继续处理 最终递归深度次
  if (!array_.every((item) => [0, "0"].includes(item[options.pid]))) {
    return arrayToTree(array_, options);
  } else {
    return array_;
  }
}

export function arrayToMap(array, key, pkey, childKey) {
  if (!array) {
    return;
  }
  var map = {};
  for (var i = 0; i < array.length; i++) {
    map[array[i][key]] = array[i];
  }
  var tree = [];
  for (var j = 0; j < array.length; j++) {
    var menu = array[j];
    if (menu[pkey] && map[menu[pkey]]) {
      var parent = map[menu[pkey]]; //获取父节点数据
      if (parent[childKey]) {
        parent[childKey].push(menu);
      } else {
        parent[childKey] = [menu];
      }
    } else {
      tree.push(menu);
    }
  }
  return { map: map, tree: tree };
}

//动态添加路由
export function addDynamicMenuRoute(value) {
  var flag = true;
  var routeArr = JSON.parse(
    sessionStorage.getItem("DYNAMIC_MENU_ROUTE") || "[]"
  );

  var childrens =
    this.$router.options.routes[this.$router.options.globalRoutesLen].children;
  var len = childrens.length;
  if (len > 0) {
    for (var i = len - 1; i >= 0; i--) {
      if (childrens[i].name == value.name) {
        flag = false;
        this.$router.options.routes[
          this.$router.options.globalRoutesLen
        ].children[i] = value;
        break;
      }
    }
  }

  if (flag) {
    routeArr.push(value);
    this.$router.options.routes[
      this.$router.options.globalRoutesLen
    ].children.push(value);
    sessionStorage.setItem("DYNAMIC_MENU_ROUTE", JSON.stringify(routeArr));
  }

  this.$router.matcher = new Router({
    routes: this.$router.options.routes,
  }).matcher;

  this.$router.push({ name: value.name });
}

export function hashCode(str) {
  var hash = 0,
    i,
    chr;
  if (str.length === 0 || typeof str !== "string") return hash;
  for (i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
}
